'use strict';

const db = uniCloud.database()
const $ = db.command.aggregate 
const dbCmd = db.command

exports.main = async (event, context) => {
	const {
		userId,
		articleId,
		content,
		commentId = '',
		replyId = '', // 子回复ID
		isReply = false
	} = event
	
	let user = await db.collection('user').doc(userId).get()
		// 获取用户对象
		user = user.data[0]
		// 获取当前的文章信息
		const article = await db.collection('article').doc(articleId).get()
		// 获取文章下的所有评论
		const comments = article.data[0].comments
	
		let commentObj = {
			comment_id: genId(5), // 评论id
			comment_content: content, // 评论内容
			create_time: new Date().getTime(), // 创建时间
			is_reply:isReply, // 却分主回复，还是子回复 
			author: {
				author_id: user._id, // 作者id
				author_name: user.author_name, // 作者名称
				avatar: user.avatar, // 作者头像
				professional: user.professional // 专业
			},
			replys: []
		}
	
		// 评论文章
		if (commentId === '') {
			commentObj.replys = []
			commentObj = dbCmd.unshift(commentObj)
		} else {
			// 回复对文章的评论
			// 获取评论索引
			let commentIndex = comments.findIndex(item => item.comment_id === commentId)
	
		
			let commentAuthor = ''
			if(isReply){
				// 子回复
				commentAuthor = comments[commentIndex].replys.find(item=>item.comment_id === replyId)
			}else{
				// 主回复
				// 获取作者信息
				commentAuthor = comments.find(item => item.comment_id === commentId)
			}
			commentAuthor = commentAuthor.author.author_name
			commentObj.to = commentAuthor
			
			// 更新回复信息
			commentObj = {
				[commentIndex]: {
					replys: dbCmd.unshift(commentObj)
				}
			}
	
		}
	
		await db.collection('article').doc(articleId).update({
			comments: commentObj
		})
	
		//返回数据给客户端
		return {
			code: 200,
			msg: "数据更新成功"
		}
	
}

function genId(length) {
		return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36)
	}
	
